<template>
  <div class="app-container">
    <h1 class="title">添加管理用户</h1>
    <el-button type="primary" icon="el-icon-plus" @click="handleAddRole">新建用户</el-button>
    <h1 class="title">搜索管理用户</h1>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="用户名称">
        <el-input v-model="formInline.id" placeholder="用户名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
        <el-button type="primary" @click="onSearch" icon="el-icon-search">搜索</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <!-- <el-table-column align="center" label="角色" width="220">
        <template slot-scope="scope">
          {{ scope.row.key }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="用户名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete"  @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'新建用户'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="用户名">
          <el-input v-model="role.name" placeholder="输入用户名" clearable/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input show-password v-model="role.description" placeholder="输入密码" clearable/>
        </el-form-item>
        <el-form-item label="用户权限选项">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            :default-expanded-keys='role.resourceIds'
            :default-checked-keys="role.resourceIds"
            node-key="roleId"
            class="permission-tree"
            @check="handleCheckChange"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenusList,addUser,getUserList,deleteUser ,getUserRoleList,getUserDetails,editedUser} from "@/api";
import md5 from 'js-md5';

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  inject: ['reload'],
  data() {
    return {
      tableloading : false,
      formInline: {
        id: '',
      },
      role: {
        userId : '',
        name : '',
        description : '',
        resourceIds : []
      },
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: '',
        label: 'roleName'
      },
      routesData : ''
    }
  },

  created() {
    this.getUserList();
    this.getRoleList();
  },
  watch: {
      'role.resourceIds': function(newVal,oldVal){
          this.role.resourceIds = newVal
      },
  },

  methods: {
    handleCheckChange() {
      let getNodes = this.$refs.tree.getCheckedNodes();
      let resourceIds = [];
            for (let index = 0; index < getNodes.length; index++) {
              let element = getNodes[index].roleId;
                  resourceIds.push(element);
            }
            this.role.resourceIds = resourceIds;
    },
        ///////搜索
    onSearch(){
        this.getUserList();
    },
    ////获取用户列表
    getUserList() {
      this.tableloading = true;
      let formData = {
        start : 0,
        length : 10,
        search : this.formInline.id
      }
      getUserList(formData).then(response => {
        if (response.data) {
          this.tableloading = false;
            this.rolesList = response.data;
        } else {
          this.tableloading = false;
          this.$message.error("response.msg");
        }
      }, response => {

      });

    },
     ////获取菜单权限选项列表
    getRoleList() {
      let formData = {}
      getUserRoleList(formData).then(response => {
        if ('0' == response.code) {
            this.routesData = response.data;
        } else {
          this.$message.error(response.msg);
        }
        
      }, response => {

      });
    },
     ////添加用户
    addUser() {
      let formData = {
        userName : this.role.name,
        passwd : md5(this.role.description),
        roleIds : this.role.resourceIds
      }
      addUser(formData).then(response => {
        if ('0' == response.code) {
            this.getUserList();
        } else {
          this.$message.error(response.msg);
        }
      }, response => {

      });
    },
    ////编辑用户
    editedUser() {
      let formData = {
        userId : this.role.userId,
        userName : this.role.name,
        passwd : this.role.description,
        roleIds : this.role.resourceIds
      }
      editedUser(formData).then(response => {
        if ('0' == response.code) {
            this.getUserList();
        } else {
          this.$message.error(response.message);
        }
      }, response => {

      });
    },
     ////删除用户
    deleteUser(userId) {
      let formData = {
        userId : userId,
      }
      deleteUser(formData).then(response => {
        if ('0' == response.code) {
          sessionStorage.removeItem('userInfo')
            this.getUserList();
        } else {
          this.$message.error(response.message);
        }
      }, response => {

      });
    },

    ////获取用户详情
    getUserDetails(roleid){
      let formData = {
        userId : roleid,
      }
      let resourceIds = [];
      getUserDetails(formData).then(response => {
        if ('0' == response.code) {
            this.role.name = response.data.userName;
            this.role.description = response.data.passwd;
            for (let index = 0; index < response.data.roleList.length; index++) {
              let element = response.data.roleList[index].roleId;
                  resourceIds.push(element);
            }
            this.role.resourceIds = resourceIds;
        } else {
          this.$message.error(response.msg);
        }
      }, response => {
      });
    },
    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.role.userId = scope.row.userId;
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.$nextTick(() => {
        this.getUserDetails(scope.row.userId);
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.deleteUser(row.userId);
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除!'
          })
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    cancelRole(){
       this.dialogVisible = false;
       this.reload();
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
          this.editedUser();
      } else {
        this.addUser();
      }
      this.reload();
      this.dialogVisible = false
      this.$notify({
        title: '成功',
        dangerouslyUseHTMLString: true,
        // message: `
        //     <div>Role Key: ${key}</div>
        //     <div>Role Name: ${name}</div>
        //     <div>Description: ${description}</div>
        //   `,
        type: 'success'
      })
    },

    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .title{
    font-weight: bold;
    color: #9e9e9e;
    padding: 10px 0;
    margin: 20px 0 40px 0;
    border-bottom: 1px solid #E0E0E0;
  }
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
